import scipy.io as scio
import mcubes
import numpy as np
import os
from PyCmpltrtok.common import sep, get_dir_name_ext, rand_name_on_now

sep('Prepare for saving')
xdir, xbase, xext = get_dir_name_ext(os.path.abspath(__file__))
save_dir = os.path.join(xdir, '_save', xbase)
os.makedirs(save_dir, exist_ok=True)

sep('Load bfm')
bfm = scio.loadmat('/var/asuspei/large_data/face/bfm/__workspace/PublicMM1/01_MorphableModel.mat')

vertices = bfm['shapeMU']
triangles = bfm['tl']

vertices = vertices.reshape(-1, 3)
# vertices = np.transpose(vertices, [1, 0])
vertices = vertices.copy()
print('vertices', vertices.shape)

triangles = triangles.copy()
triangles -= 1
print('triangles', triangles.shape)

sep('Extract dae')
dae_path = os.path.join(save_dir, f'bfm2dae.dt{rand_name_on_now()}.dae')
print(f'Extracting to {dae_path}')
mcubes.export_mesh(vertices, triangles, dae_path, "BFM2dae")
print(f'Extracted.')

sep('All over')